package cc.shacocloud.mirage.demo.kotlin.config

import cc.shacocloud.mirage.bean.InitializingBean
import cc.shacocloud.mirage.bean.bind.Configuration
import cc.shacocloud.mirage.env.Environment
import cc.shacocloud.mirage.env.EnvironmentAware
import cc.shacocloud.mirage.env.bind.EnvValue
import cc.shacocloud.mirage.kotlin.Slf4j
import cc.shacocloud.mirage.kotlin.Slf4j.Companion.log
import io.vertx.core.Vertx
import java.lang.IllegalArgumentException

/**
 * @author 思追(shaco)
 * @date 2023/3/6
 */
@Slf4j
@Configuration
class MirageDemoConfiguration(
    private val mirageDemoProperties: MirageDemoProperties,
    private val vertx: Vertx
) : InitializingBean, EnvironmentAware {

    private lateinit var environment: Environment

    private lateinit var dev1: String

    @EnvValue("\${mirage.demo.dev1}")
    fun setDev1(dev1: String) {
        this.dev1 = dev1;
    }

    override fun setEnvironment(environment: Environment) {
        this.environment = environment
    }

    override fun init() {
        log.info("dev配置数据：${mirageDemoProperties.dev}")
        log.info("dev1配置数据：${mirageDemoProperties.dev1}")

        val dev = environment.getProperty("mirage.demo.dev", String::class.java)
        assertOrThrow(mirageDemoProperties.dev == dev)

        val dev1 = environment.getProperty("mirage.demo.dev1", String::class.java)
        assertOrThrow(mirageDemoProperties.dev1 == dev1)
        assertOrThrow(this.dev1 == dev1)

        // 定时获取配置信息如果配置发生变更，打印的值将发生改变
        vertx.setPeriodic(5000, 5000) {
            log.info("dev1配置数据：${mirageDemoProperties.dev1}")
        }
    }


    private fun assertOrThrow(boo: Boolean) {
        if (!boo) {
            throw IllegalArgumentException()
        }
    }
}